use regex::Regex;
use std::fs::{self};
use std::io::Write;
use std::os::windows::process::CommandExt;
use std::{
    env,
    io::{self, BufRead},
    process::{Command, Stdio},
};
use tauri::{Manager, Window};

#[derive(Clone, serde::Serialize)]
struct Payload {
    message: String,
    current_dir: String,
}
#[tauri::command]
pub async fn run_clewd(port: String, window: Window) {
    let command = Command::new("node")
        .args(["clewd/clewd.js", &port])
        .creation_flags(0x08000000)
        .stdout(Stdio::piped())
        .spawn();
    let mut child = match command {
        Ok(child) => child,
        Err(e) => {
            eprintln!("Failed to start command: {}", e);
            std::process::exit(1);
        }
    };
    if let Some(stdout) = child.stdout.take() {
        let reader = io::BufReader::new(stdout);
        for line in reader.lines() {
            match line {
                Ok(text) => {
                    if let Ok(current_dir) = env::current_dir() {
                        // 将 PathBuf 转换为 String
                        window
                            .emit_all(
                                "clewd_cmd",
                                Payload {
                                    message: text.into(),
                                    current_dir: current_dir.to_string_lossy().into_owned().into(),
                                },
                            )
                            .unwrap();
                    } else {
                        eprintln!("无法获取当前工作目录");
                    }
                }
                Err(e) => eprintln!("Error reading line: {}", e),
            }
        }
    }
}
#[tauri::command]
pub fn set_cookie(cookie: String) {
    let file_path = "clewd/config.js";
    // 读取文件内容
    let file_content = match fs::read_to_string(file_path) {
        Ok(content) => content,
        Err(e) => {
            eprintln!("Error reading file: {}", e);
            return;
        }
    };
    // 使用正则表达式替换 Cookie 的值
    let pattern = r#""Cookie":\s*"\s*[^"]*\s*""#;
    let regex = Regex::new(pattern).unwrap();
    let new_pattern = format!(r#""Cookie": "{}""#, cookie);
    let updated_content = regex.replace_all(&file_content, new_pattern);

    // 将修改后的内容写回文件
    if let Err(e) = write_to_file(file_path, &updated_content.to_string()) {
        eprintln!("Error writing to file: {}", e);
    }
}

fn write_to_file(file_path: &str, content: &str) -> io::Result<()> {
    let mut file = fs::File::create(file_path)?;
    file.write_all(content.as_bytes())?;
    Ok(())
}
